Python for Loop (with Examples)
π Let's Get Loopy: The Wild World of Python for
Loops! πβ
So you're about to dive into the magical land of Python for
loops? Buckle up, because you're going to repeat stuff until your code is so efficient it basically does the work for you. Think of a for
loop as a fancy robot that goes through each item in a sequence and does your bidding.
Python lets you for
loop through almost everything:
- π List
- π Tuple
- π Dictionary
- π Set
- π§΅ String
- π Range
π§ The Loop Blueprintβ
for val in sequence:
statement(s)
Here, val
is the super cool intern youβve hired to go through your sequence and handle each item one by one. When the sequence is doneβboom! The loop peaces out.
1. π€Ή Python for
Loop with Listβ
Youβve got a list of names. You want to greet them. Letβs loop!
names = ["alex", "brian", "charles"]
for x in names:
print('Current name is :', x)
π¨οΈ Output:
Current name is : alex
Current name is : brian
Current name is : charles
2. π§΅ Looping Through a Tuple (fancy list that canβt be changed)β
mytuple = ("item1", "item1", "item3")
for e in mytuple:
print("Current item is", e)
π¨οΈ Output:
Current item is item1
Current item is item1
Current item is item3
3. π Looping Through a Dictionaryβ
Dictionaries are like little boxes with labels and things inside. You can loop over keys, values, or both!
colors_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in colors_dict.keys():
print(key)
for item in colors_dict.items():
print(item)
π¨οΈ Output:
color
fruit
pet
('color', 'blue')
('fruit', 'apple')
('pet', 'dog')
4. π Looping Through a Setβ
Sets are like bags of random things. Order is not guaranteed. Surprises await!
myset = set(["item1", "item2", "item3"])
for e in myset:
print("Current item is", e)
π¨οΈ Output (order may vary!):
Current item is item3
Current item is item2
Current item is item1
5. π€ Looping Through a Stringβ
Strings = chains of characters. Time to inspect each letter like a detective π΅οΈ.
name = "alex"
for x in name:
print("Current char is", x)
π¨οΈ Output:
Current char is a
Current char is l
Current char is e
Current char is x
6. π― Looping with range()
β
Want to count stuff? Say hello to range()
β Python's built-in number line.
for i in range(5):
print(i)
π¨οΈ Output:
0
1
2
3
4
7. β break
and πΊ continue
β Drama in the Loopβ
Break: "Iβm done. Bye!"β
names = ["alex", "brian", "charles"]
print("Loop started")
for x in names:
print(x)
if x == "brian":
break;
print("Loop ended")
π¨οΈ Output:
Loop started
alex
brian
Loop ended
Continue: "Skip this one, move along!"β
names = ["alex", "brian", "charles"]
print("Loop started")
for x in names:
if x == "brian":
continue;
print(x)
print("Loop ended")
π¨οΈ Output:
Loop started
alex
charles
Loop ended
8. π© for
...else
: The Plot Twist Endingβ
When the loop ends without any interruptions (break
), the else
gets its moment to shine.
names = ["alex", "brian", "charles"]
for x in names:
print(x)
else:
print("No name is left in the list")
π¨οΈ Output:
alex
brian
charles
No name is left in the list
Got questions? Confused by sets or strings? π§
Drop me your doubts β and remember...
π Happy Looping, Pythonistas! π